﻿using BLL;
using Model;
using PushSharp;
using PushSharp.Android;
using PushSharp.Apple;
using PushSharp.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace PushMessage
{
    class Program
    {
        static void Main(string[] args)
        {
            //注册 當前程序未處理異常事件
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(currAppdomain_UnhandledException);
            string cmd = args[0].Trim();

            switch (cmd)
            {
                case "StartApple":
                    StartApple();
                    break;
                case "Datatransfer":
                    Datatransfer();
                    break;
            }
            //System.Threading.Thread.Sleep(5000);
        }

        public static void Datatransfer()
        {
            //List<Pendingpushmessage> list = PendingpushmessageBLL.CurrBll.GetListSent();
            //for (int i = 0; i < list.Count; i++)
            //{
            //    PendingpushmessageBLL.CurrBll.AddList(list[i].Id, list[i].Messagecontent, list[i].Devicelist, list[i].Type);
            //}
        }

        public static void StartApple()
        {
            Log.AddLog("Start.....");
            List<Pendingpushmessage> list = PendingpushmessageBLL.CurrBll.GetList();

            if (list == null)
            {
                Log.AddLog("list == null");
                return;
            }

            if (list.Count == 0)
            {
                Log.AddLog("list.Count==0");
                return;
            }

            var push = new PushBroker();

            //Wire up the events for all the services that the broker registers
            push.OnNotificationSent += NotificationSent;
            push.OnChannelException += ChannelException;
            push.OnServiceException += ServiceException;
            push.OnNotificationFailed += NotificationFailed;
            push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
            push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
            push.OnChannelCreated += ChannelCreated;
            push.OnChannelDestroyed += ChannelDestroyed;
            for (int i = 0; i < list.Count; i++)
            {
                //Create our push services broker
               
                if (list[i].Certificate != null && list[i].Certificate != "")
                {
                    #region iOS推送
                    int mId = list[i].Id;
                    var deviceTokenArray = DeviceBLL.CurrBll.GetDeviceList(1, mId);
                    //Registering the Apple Service and sending an iOS Notification
                    //var certPath = "AblePush.p12";//证书路径
                    //var certPwd = "ableable";//证书密码
                    var certPath = AppDomain.CurrentDomain.BaseDirectory+list[i].Certificate;//证书路径
                    var certPwd = list[i].PassWord;//证书密码
                    if (File.Exists(certPath) && deviceTokenArray != null && deviceTokenArray.Length != 0)
                    {
                       
                        //var msg = "test by alon at " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");//消息
                        var msg = list[i].Messagecontent;//消息
                        var data = list[i].Data;
                        //var deviceTokenArray = new string[] { "3eb3006baeb2bb09990b90f601007c8d85ccb7df5e8258562f84eac7db5a8484" };//手机序列号数组

                        var appleCert = File.ReadAllBytes(certPath);
                        push.RegisterAppleService(new ApplePushChannelSettings(appleCert, certPwd));
                        foreach (var deviceToken in deviceTokenArray)
                        {
                            push.QueueNotification(new AppleNotification()
                                                   .ForDeviceToken(deviceToken)
                                                   .WithAlert(msg)
                                                   .WithBadge(0)
                                                   .WithCategory(data)
                                                   .WithSound("sound.caf")
                                                   .WithTag(mId)
                                                   );
                            DeviceBLL.CurrBll.UpDateStatus(mId, deviceToken);
                        }
                    }
                    if (!File.Exists(certPath))
                    {
                        Log.AddLog(certPath);
                    }
                    //else
                    //{
                    //    throw new Exception("证书不存在");
                    //}
                    #endregion
                }
                if (list[i].SenderId != null && list[i].SenderId != "")
                {
                    #region Android推送
                    int mId = list[i].Id;
                    var deviceTokenArray = DeviceBLL.CurrBll.GetDeviceList(2, mId);
                    if (deviceTokenArray != null && deviceTokenArray.Length != 0)
                    {
                        //var senderId = "711746258923";//项目Id
                        //var authorizationToken = "AIzaSyB7bBjgKFXM-mI8yR95lgPty8QXX5txnH0";//授权令牌
                        //var packageName = "com.able.mobile.push";
                        var senderId = list[i].SenderId;//项目Id
                        var authorizationToken = list[i].AuthorizationToken;//授权令牌
                        var packageName = list[i].PackageName;
                        //var deviceRegistrationId = "APA91bEM2wjwIggEW7tCmM85Cs4PP7vpzrUwHoYU-u9euzmGm_GxC7Au8nw0v8VupNy126eWc_ohH20ooXAPBSKsGP4q7VlGJw7AAmXiK9NSyqMCgIvczNAKTz4TYPb7knnZqgOPu7Bx";//设备注册Id

                        //var deviceRegistrationIdList = new List<string>();//设备Id集合
                        //deviceRegistrationIdList.Add("APA91bEM2wjwIggEW7tCmM85Cs4PP7vpzrUwHoYU-u9euzmGm_GxC7Au8nw0v8VupNy126eWc_ohH20ooXAPBSKsGP4q7VlGJw7AAmXiK9NSyqMCgIvczNAKTz4TYPb7knnZqgOPu7Bx");
                        //deviceRegistrationIdList.Add("APA91bEM2wjwIggEW7tCmM85Cs4PP7vpzrUwHoYU-u9euzmGm_GxC7Au8nw0v8VupNy126eWc_ohH20ooXAPBSKsGP4q7VlGJw7AAmXiK9NSyqMCgIvczNAKTz4TYPb7knnZqgOPu7Bx");

                        //var msg = "test by alon at " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");//消息
                        var msg = list[i].Messagecontent;//消息
                        var data = list[i].Data;
                        object objJson = new
                        {
                            alert = msg,
                            data = data,
                            badge = 1,
                            sound = "sound.caf",
                        };
                        var strJson = Newtonsoft.Json.JsonConvert.SerializeObject(objJson);

                        //Registering the GCM Service and sending an Android Notification
                        push.RegisterGcmService(new GcmPushChannelSettings(senderId, authorizationToken, packageName));
                        //Fluent construction of an Android GCM Notification
                        //IMPORTANT: For Android you MUST use your own RegistrationId here that gets generated within your Android app itself!

                        //推送给多台设备
                        //var gcmNoti = new GcmNotification();
                        //gcmNoti.RegistrationIds = new List<String>(deviceTokenArray);
                        //push.QueueNotification(gcmNoti.WithJson(strJson));

                        foreach (var deviceToken in deviceTokenArray)
                        {
                            push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(deviceToken).WithJson(strJson).WithTag(mId));//单独推送给指定设备
                            DeviceBLL.CurrBll.UpDateStatus(mId, deviceToken);
                        }
                    }
                    #endregion
                }
               
            }
            push.StopAllServices();
            Log.AddLog("Waiting for Queue to Finish...");
            //Stop and wait for the queues to drains


            Log.AddLog("Queue Finished, press return to exit...");

        }

        static void DeviceSubscriptionChanged(object sender, string oldSubscriptionId, string newSubscriptionId, INotification notification)
        {
            //Currently this event will only ever happen for Android GCM
            Log.AddLog("Device Registration Changed:  Old-> " + oldSubscriptionId + "  New-> " + newSubscriptionId + " -> " + notification);
        }

        static void NotificationSent(object sender, INotification notification)
        {
            Log.AddLog("Sent: " + sender + " -> " + notification);
            //string devicetoken = "";
            //int mId = 0;
            //if (sender.ToString().Equals("PushSharp.Apple.ApplePushService"))//Apple 
            //{
            //    devicetoken = (notification as PushSharp.Apple.AppleNotification).DeviceToken;
            //    mId = Convert.ToInt32((notification as PushSharp.Apple.AppleNotification).Tag);
            //}
            //else//Android
            //{
                
            //    devicetoken = (notification as PushSharp.Android.GcmNotification).RegistrationIds[0];
            //    mId = Convert.ToInt32((notification as PushSharp.Android.GcmNotification).Tag);
            //}
            //DeviceBLL.CurrBll.UpDateStatus(mId, devicetoken);
        }

        static void NotificationFailed(object sender, INotification notification, Exception notificationFailureException)
        {
            Log.AddLog("Failure: " + sender + " -> " + notificationFailureException.Message + " -> " + notification);
            //string devicetoken = "";
            //int mId = 0;
            //if (sender.ToString().Equals("PushSharp.Apple.ApplePushService"))//Apple
            //{
            //    devicetoken = (notification as PushSharp.Apple.AppleNotification).DeviceToken;
            //    mId = Convert.ToInt32((notification as PushSharp.Apple.AppleNotification).Tag);
            //}
            //else//Android
            //{
            //    devicetoken = (notification as PushSharp.Android.GcmNotification).RegistrationIds[0];
            //    mId = Convert.ToInt32((notification as PushSharp.Android.GcmNotification).Tag);
            //}
            //DeviceBLL.CurrBll.UpdateCount(mId, devicetoken);
        }

        static void ChannelException(object sender, IPushChannel channel, Exception exception)
        {
            Log.AddLog("Channel Exception: " + sender + " -> " + exception);
        }

        static void ServiceException(object sender, Exception exception)
        {
            Log.AddLog("Service Exception: " + sender + " -> " + exception);
        }

        static void DeviceSubscriptionExpired(object sender, string expiredDeviceSubscriptionId, DateTime timestamp, INotification notification)
        {
            Log.AddLog("Device Subscription Expired: " + sender + " -> " + expiredDeviceSubscriptionId);
        }

        static void ChannelDestroyed(object sender)
        {
            Log.AddLog("Channel Destroyed for: " + sender);
        }

        static void ChannelCreated(object sender, IPushChannel pushChannel)
        {
            Log.AddLog("Channel Created for: " + sender);
        }

        #region 當前程序未處理異常事件
        /// <summary>
        /// 當前程序未處理異常事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void currAppdomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Log.AddErrorLog(e.ExceptionObject.ToString());
            Environment.Exit(0);
        }
        #endregion

    }
}
